var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
// var logger = require("morgan");

var indexRouter = require("./routes/index");
var adminRouter = require("./routes/admin");
var roleRouter = require("./routes/role");
var apiRouter = require("./routes/login");
// 导入封装好的jwt对象
const jwt = require("./utils/jwt");

var app = express();
// 导入cors中间件处理跨域
const cors = require("cors");
app.use(
  cors({
    exposedHeaders: ["Authorization"],
  })
);

// express框架模板存放的位置是什么
app.set("views", path.join(__dirname, "views"));
// express框架模板的默认后缀是什么
app.set("view engine", "ejs");

// app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 验证token
app.use((req, res, next) => {
  if (req.url.includes("login")) {
    next();
    return;
  }
  if (req.url.includes("register")) {
    next();
    return;
  }
  const token = req.headers["authorization"]?.split(" ")[1];
  if (token) {
    const payload = jwt.verify(token);
    if (payload) {
      const newToken = jwt.generate(
        {
          loginID: payload.loginID,
        },
        "1h"
      );
      req.header("Authorization", newToken);
      next();
    } else {
      res.status(401).send({ errCode: -1, errInfo: "token已过期" });
    }
  } else {
    next();
  }
});

// ----------------------------------------------------------------------
app.use("/", indexRouter);
app.use("/api", apiRouter);
app.use("/role", roleRouter);
app.use("/admin", adminRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

app.listen(8000, () => {
  console.log("启动服务");
});

module.exports = app;
